//
//  UIViewController+Ext.m
//  Weike
//
//  Created by leirz on 15/4/28.
//  Copyright (c) 2015年 winupon. All rights reserved.
//

#import <objc/runtime.h>
#import "UIViewController+Ext.h"

static void *animatingKey = (void *)@"animatingKey";

@implementation UIViewController (Ext)

- (BOOL)animating
{
    NSNumber *value = objc_getAssociatedObject(self, animatingKey);
    if (value == nil) {
        return NO;
    }
    return value.boolValue;
}

- (void)setAnimating:(BOOL)animating
{
    objc_setAssociatedObject(self, animatingKey, [NSNumber numberWithBool:animating], OBJC_ASSOCIATION_COPY_NONATOMIC);
}

@end



@implementation UINavigationController (ShouldPopOnBackButton)

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem*)item {
    
    if([self.viewControllers count] < [navigationBar.items count]) {
        return YES;
    }
    
    BOOL shouldPop = YES;
    UIViewController* vc = [self topViewController];
    if([vc respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
        shouldPop = [vc navigationShouldPopOnBackButton];
    }
    
    if(shouldPop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self popViewControllerAnimated:YES];
        });
    } else {
        // Workaround for iOS7.1. Thanks to @boliva - http://stackoverflow.com/posts/comments/34452906
        for(UIView *subview in [navigationBar subviews]) {
//            if(subview.alpha < 1.) {
//                [UIView animateWithDuration:.25 animations:^{
//                    subview.alpha = 1.;
//                }];
//            }
        }
    }
    
    return NO;
}

@end